﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Resources;
using System.Reflection;
using Tesla.Service.DataContracts;
using Tesla.Util.Utilities;
using Tesla.Util.UIUtilities;
//using Microsoft.Practices.EnterpriseLibrary.Caching;
//using Microsoft.Practices.EnterpriseLibrary.Common;
//using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
//using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
//using Microsoft.Practices.EnterpriseLibrary.Logging;




namespace Tesla.Web
{
    public class PageBase :Page 
    {
        private const string GADN_CUSTOM_EXCEPTION_TYPE = "Tesla.Util.Utilities.GADNCustomException";

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                bool isSessionTimeoutDivToBeDisplayed = Convert.ToBoolean(ConfigurationSettings.AppSettings["IsSessionTimeoutDivToBeDisplayed"].ToString());
                

                if (isSessionTimeoutDivToBeDisplayed)
                {
                    int gadnPollingInterval = Convert.ToInt32(ConfigurationSettings.AppSettings["GADNPollingInterval"].ToString());
                    
                    StringBuilder sb = new StringBuilder();
                    sb.Append("<script language='javascript'>\n");
                   
                    sb.Append("var ActivityDetectedFlag = false;\n");
                    sb.Append("var lastX = 0;\n");
                    sb.Append("var lastY = 0;\n");
                    sb.Append("PageInitialize();\n");
                    sb.Append("function PageInitialize() {\n");
                    sb.Append("    EnableScheduledMethod();\n");
                    sb.Append("}\n");
                    sb.Append("function EnableScheduledMethod() {\n");
                    sb.Append("    window.setTimeout(TestActivityOccurrance,\n");
                    sb.Append(gadnPollingInterval);
                    sb.Append(")\n");
                    sb.Append("    document.onmousemove = SetActivity;\n");
                    sb.Append("    document.onkeyup = SetActivity;\n");
                    sb.Append("}\n");
                    sb.Append("function TestActivityOccurrance() {\n");
                    sb.Append("    if (true == ActivityDetectedFlag) {\n");
                    sb.Append("        EnableScheduledMethod();\n");
                    sb.Append("        ActivityDetectedFlag = false;\n");
                    sb.Append("    }\n");
                    sb.Append("    else {\n");
                    sb.Append("alert('You will be automatically redirected as your session has been inactive for last " + gadnPollingInterval/(60000) + " minute(s).');\n");
                    sb.Append(" if (window.location.href.indexOf('Users',0) !=-1){");
                    sb.Append("window.location.href(window.location.href.substring(0,window.location.href.indexOf('Pages', 0) -1) + '/Pages/Users/WhoIAm.aspx');}\n");
                    sb.Append(" else{");
                    sb.Append("window.location.href(window.location.href.substring(0,window.location.href.indexOf('Pages', 0) -1) + '/Pages/Administrator/Welcome.aspx');}\n");
                    sb.Append("    }\n");
                    sb.Append("}\n");
                    sb.Append("function SetActivity(e) {\n");
                    sb.Append("if (!e) var e = window.event;\n");
                    sb.Append("if (e.type == 'mousemove') {\n");
                    sb.Append("    var currX = event.clientX + document.body.scrollLeft;\n");
                    sb.Append("    var currY = event.clientY + document.body.scrollTop;\n");
                    sb.Append(" if ((currX != lastX) && (currY != lastY)) {\n");
                    sb.Append("     document.onmousemove = null;\n");
                    sb.Append("     document.onkeyup = null;\n");
                    sb.Append("     ActivityDetectedFlag = true;\n");
                    sb.Append(" }\n");
                    sb.Append(" lastX = currX;\n");
                    sb.Append(" lastY = currY;\n");
                    sb.Append(" }\n");
                    sb.Append(" else if (e.type == 'keyup') {\n");
                    sb.Append(" document.onmousemove = null;\n");
                    sb.Append(" document.onkeyup = null;\n");
                    sb.Append("  ActivityDetectedFlag = true;\n");
                    //sb.Append(" window.status = 'KeyUp';\n");
                    sb.Append(" }\n");
                    sb.Append(" }\n");
                    sb.Append("\n</script>");
                    ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "ShowTimeout", sb.ToString());
                }

                //ADD DIV DYNAMICALLY                
                //HtmlGenericControl dynDiv = new HtmlGenericControl("DIV");
                //string dynDivInnerHTML = string.Empty;
                //dynDiv.ID = "modalPage";
                //dynDivInnerHTML += "<div class='modalBackground'>\n";
                //dynDivInnerHTML += "</div>\n";
                //dynDivInnerHTML += "<div class='modalContainer'>\n";
                //dynDivInnerHTML += "<div class='modal'>\n";
                //dynDivInnerHTML += "<div class='modalTop'>\n";
                //dynDivInnerHTML += "</div>\n";
                //dynDivInnerHTML += "<div class='modalBody'>\n";
                //dynDivInnerHTML += "<table>\n";
                //dynDivInnerHTML += "<tr>\n";
                //dynDivInnerHTML += "<td>\n";
                //dynDivInnerHTML += "<span class='Tesla_Standard_Label' style='font-weight:normal'>You will be redirected to 'Who Am I' screen as your session has been inactive for last 30 minutes.</span>\n";
                ////dynDivInnerHTML += "If you want to continue click OK.Clicking on Cancel will close the window and all unsaved data will be lost </span>\n";
                //dynDivInnerHTML += "</td>\n";
                //dynDivInnerHTML += "</tr>\n";
                //dynDivInnerHTML += "<tr>\n";
                //dynDivInnerHTML += "<td>\n";
                //dynDivInnerHTML += "<input type='button' value='OK' class='Tesla_Standard_Button' onclick = \"window.location.href('../Users/WhoIAm.aspx')\"/>\n";
                //dynDivInnerHTML += "</td>\n";
                ////dynDivInnerHTML += "<td style='padding-left:10px'>\n";
                ////dynDivInnerHTML += "<input type='button' value='Cancel' class='Tesla_Standard_Button' onclick='window.close()' />\n";
                ////dynDivInnerHTML += "</td>\n";
                //dynDivInnerHTML += "</tr>\n";
                //dynDivInnerHTML += "</table>\n";
                //dynDivInnerHTML += "</div>\n";
                //dynDivInnerHTML += "</div>\n";
                //dynDivInnerHTML += "</div>\n";
                //dynDiv.InnerHtml = dynDivInnerHTML;
                //this.Controls.Add(dynDiv);
            }
            catch (Exception ex)
            {
                //bool rethrow = ExceptionPolicy.HandleException(ex, "GADN Custom Exception Policy");
                //throw new GADNCustomException("Some Errors have occurred in the application.", "Pagebase", "Page_Init");
            }
             
            
        }

        protected override void OnPreRender(EventArgs e)
        {
             bool browserButtonPressedWarningShown = Convert.ToBoolean(ConfigurationSettings.AppSettings["browserButtonPressedWarningShown"].ToString());

             if (browserButtonPressedWarningShown)
             {
                 base.OnPreRender(e);
                 string strDisAbleBackButton;
                 strDisAbleBackButton = "<script language='javascript'>\n";
                 strDisAbleBackButton += "window.history.forward(1);\n";
                 strDisAbleBackButton += "\n</script>";
                 ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "clientScript", strDisAbleBackButton);
                 Response.Cache.SetCacheability(HttpCacheability.NoCache);
                 Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
                 Response.Cache.SetNoStore();
             }
             else
                 base.OnPreRender(e);
        }
        
        
        
        public static byte[] CompressViewState(byte[] uncompData)
        {
            using (MemoryStream mem = new MemoryStream())
            {
                CompressionMode mode = CompressionMode.Compress;
                // Use the newly created memory stream for the compressed data.
                using (GZipStream gzip = new GZipStream(mem, mode, true))
                {
                    //Writes compressed byte to the underlying
                    //stream from the specified byte array.
                    gzip.Write(uncompData, 0, uncompData.Length);
                }
                return mem.ToArray();
            }
        }

        public static byte[] DecompressViewState(byte[] compData)
        {
            GZipStream gzip;
            using (MemoryStream inputMem = new MemoryStream())
            {
                inputMem.Write(compData, 0, compData.Length);
                // Reset the memory stream position to begin decompression.
                inputMem.Position = 0;
                CompressionMode mode = CompressionMode.Decompress;
                gzip = new GZipStream(inputMem, mode, true);


                using (MemoryStream outputMem = new MemoryStream())
                {
                    // Read 1024 bytes at a time
                    byte[] buf = new byte[1024];
                    int byteRead = -1;
                    byteRead = gzip.Read(buf, 0, buf.Length);
                    while (byteRead > 0)
                    {
                        //write to memory stream
                        outputMem.Write(buf, 0, byteRead);
                        byteRead = gzip.Read(buf, 0, buf.Length);
                    }
                    gzip.Close();
                    return outputMem.ToArray();
                }
            }
        }

        public bool HasPermissionToView(string objName, bool isTab)
        {
            string userGroupName = string.Empty; string[] availableGroups = ControlUtilities.GetConfigInformation("AvailableUserGroups").Split(',');

            foreach (string userGroup in availableGroups)
            {
                if (HttpContext.Current.User.IsInRole(userGroup))
                {
                    userGroupName = userGroup; break;
                }
            }
            return this.ResolveRoleForCurrentUser(userGroupName, objName, isTab);            
        }

        private bool ResolveRoleForCurrentUser(string userGroupName, string objName, bool isTab)
        {

            string contextName = string.Empty; XDocument xDoc = null; bool result = false;

            if (userGroupName.IndexOf(@"\") != -1)
                userGroupName = userGroupName.Substring(userGroupName.LastIndexOf(@"\") + 1, userGroupName.Length - (userGroupName.LastIndexOf(@"\") + 1));

            if (!File.Exists(Server.MapPath(ControlUtilities.GetConfigInformation("RoleScreenMappingXMLPath"))))
                throw new Exception("Please set config value for RoleScreenMappingXMLPath");
            
            if (Cache["ROLESCREENMAPPERXML"] == null)
            {
                xDoc = XDocument.Load(Server.MapPath(ControlUtilities.GetConfigInformation("RoleScreenMappingXMLPath")));
                Cache.Insert("ROLESCREENMAPPERXML", xDoc);
            }
            else
                xDoc = (XDocument)Cache["ROLESCREENMAPPERXML"];

            

            
            IList MapperContexts = isTab == true ? 
                                    (from MapperContext in xDoc.Elements("MapperContext").Elements("Tab").Attributes()
                                    where MapperContext.Value == objName && MapperContext.NextAttribute.Value == userGroupName
                                    select new
                                    {
                                        Name = MapperContext.Value,
                                        SecurityGroup = MapperContext.NextAttribute.Value,
                                        HasAccess = MapperContext.NextAttribute.NextAttribute.Value
                                    }
                                    ).ToList() :
                                    (from MapperContext in xDoc.Elements("MapperContext").Elements("Screen").Attributes()
                                     where MapperContext.Value == objName && MapperContext.NextAttribute.Value == @userGroupName
                                     select new
                                     {
                                         Name = MapperContext.Value,
                                         SecurityGroup = MapperContext.NextAttribute.Value,
                                         HasAccess = MapperContext.NextAttribute.NextAttribute.Value
                                     }
                                    ).ToList();

            if (MapperContexts != null && MapperContexts.Count == 1)
                result = Convert.ToBoolean(MapperContexts.Cast<object>().ToList()[0].GetType().GetProperties()[2].GetValue(MapperContexts.Cast<object>().ToList()[0], null));
            return result;
        }

        protected override void OnError(EventArgs e)
        {
            if (Server.GetLastError().GetType().ToString() == GADN_CUSTOM_EXCEPTION_TYPE)
            {
                this.SetSession("ErrorDetail", ((GADNCustomException)Server.GetLastError()).GenerateCustomExceptionMessage());
                //Session["ErrorDetail"] = ((GADNCustomException)Server.GetLastError()).GenerateCustomExceptionMessage();
                Response.Redirect("~/Pages/ErrorPage/GenericErrorPage.aspx");
            }
            else if (Server.GetLastError() != null && Server.GetLastError() is HttpRequestValidationException)
            {
                if (Server.GetLastError().GetBaseException().Message.Contains("rpt"))
                {
                    Response.Redirect(OnScriptingErrorRedirectURL(Server.GetLastError().GetBaseException().Message.Substring(Server.GetLastError().GetBaseException().Message.IndexOf("rpt"), Server.GetLastError().GetBaseException().Message.IndexOf("$") - Server.GetLastError().GetBaseException().Message.IndexOf("rpt"))));
                }
                else
                {
                    this.SetSession("ErrorDetail", "HTTP Request validation exception occurred!");
                    //bool rethrow = ExceptionPolicy.HandleException(Server.GetLastError(), "GADN Custom Exception Policy");
                    //Server.ClearError();
                    Response.Redirect("~/Pages/ErrorPage/GenericErrorPage.aspx");
                }
            }
        }

        public void SetSession(string key, object value)
        {
            Session[key] = value;
        }

        public object GetSession(string key)
        {
            if (Session[key] == null )
                throw new Exception("Session Timeout occurred");
            return Session[key];
        }

        private string OnScriptingErrorRedirectURL(string redirectionKey)
        {
            Hashtable htURLMapping = new Hashtable();
            string redirectionURL = string.Empty;

            htURLMapping.Add("rptConfigurationKnowledgeReportViewer", "~/Pages/Reports/Admin/ConfigurationReportKnowledge.aspx?Source=PageBaseError");
            htURLMapping.Add("rptCompletionReportViewer", "~/Pages/Reports/Admin/CompletionReport.aspx?Source=PageBaseError");
            htURLMapping.Add("rptUnitCompetencyReportViewer", "~/Pages/Reports/Admin/UnitCompetencySpreadReport.aspx?Source=PageBaseError");
            htURLMapping.Add("rptReportAQueryReportViewer", "~/Pages/Reports/User/ReportAQuery.aspx?Source=PageBaseError");

            redirectionURL = htURLMapping[redirectionKey].ToString();
            return redirectionURL;
        }

    }

}
